/**
 * 
 */
package com.jsync.util;

import java.util.HashMap;
import java.util.Map;

import com.jsync.model.Resource;

/**
 * @author prabz
 * 
 */
public final class SingletonFactory {

	private Map<Class, Object> map;
	private static SingletonFactory sfy;

	/**
	 * 
	 */
	protected SingletonFactory() {
		map = new HashMap<Class, Object>();
	}

	/**
	 * @return
	 * @throws Exception
	 */
	public static SingletonFactory getInstance() {
		try{
			if (sfy == null) {
				sfy = new SingletonFactory();
			}			
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return sfy;
	}

	/**
	 * @param cl
	 * @return
	 * @throws Exception
	 */
	public Object get(Class cl) {
		Object obj = map.get(cl);
		try {
			if (obj == null) {
				obj = cl.newInstance();
				map.put(cl, obj);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return obj;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			Resource resource = (Resource) SingletonFactory.getInstance().get(
					Resource.class);
			System.out.println("Resource First time---> " + resource);
			resource = (Resource) SingletonFactory.getInstance().get(
					Resource.class);
			System.out.println("Resource Second time---> " + resource);
			resource = (Resource) SingletonFactory.getInstance().get(
					Resource.class);
			System.out.println("Resource Third time---> " + resource);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
